﻿using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.EntityFrameworkCore.EFPlus;
using Abp.Extensions;
using Abp.Linq.Extensions;
using Abp.UI;
using ARchGL.Platform.Authorization.Users;
using ARchGL.Platform.Core;
using ARchGL.Platform.Dtos;
using ARchGL.Platform.Juneng;
using ARchGL.Platform.Utils;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ARchGL.Platform.Application
{
    /// <summary>
    /// 安全检查 实现
    /// </summary>
    [AbpAuthorize]
    public class SecurityChecksAppService : PlatformAppServiceBase, ISecurityChecksAppService
    {
        private readonly IRepository<SelfChecks, Guid> selfChecksRepository;
        private readonly IRepository<SecurityChecks, Guid> securityChecksRepository;
        private readonly IRepository<SecurityCheckItems, Guid> securityCheckItemsRepository;
        private readonly IRepository<SecurityCheckAndFeedbacks, Guid> securityCheckAndFeedbacksRepository;
        private readonly IRepository<SecurityChecksTurnOverHistorys, Guid> securityChecksTurnOverHistorysRepository;
        private readonly IRepository<Attachments, Guid> attachmentsRepository;
        private readonly IRepository<OrganizationUnitExtend, long> organizationUnitExtendRepository;
        private readonly IRepository<Projects, Guid> projectsRepository;
        private readonly INoticesAppService noticesAppService;

        public SecurityChecksAppService(IRepository<SecurityChecks, Guid> _securityChecksRepository, IRepository<Attachments, Guid> _attachmentsRepository,
            IRepository<SecurityCheckItems, Guid> _securityCheckItemsRepository, IRepository<SecurityCheckAndFeedbacks, Guid> _securityCheckAndFeedbacksRepository,
            IRepository<SelfChecks, Guid> _selfChecksRepository, IRepository<SecurityChecksTurnOverHistorys, Guid> _securityChecksTurnOverHistorysRepository,
            INoticesAppService _noticesAppService, IRepository<Projects, Guid> _projectsRepository,
            IRepository<OrganizationUnitExtend, long> _organizationUnitExtendRepository)
        {
            selfChecksRepository = _selfChecksRepository;
            securityChecksRepository = _securityChecksRepository;
            securityCheckItemsRepository = _securityCheckItemsRepository;
            securityCheckAndFeedbacksRepository = _securityCheckAndFeedbacksRepository;
            securityChecksTurnOverHistorysRepository = _securityChecksTurnOverHistorysRepository;
            attachmentsRepository = _attachmentsRepository;
            noticesAppService = _noticesAppService;
            organizationUnitExtendRepository = _organizationUnitExtendRepository;
            projectsRepository = _projectsRepository;
        }

        #region 巡检

        /// <summary>
        /// 新建巡检
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<Guid> CreateCheck(SecurityChecksInput input)
        {
            if (input.Id == Guid.Empty)
            {//新增
                var entity = ObjectMapper.Map<SecurityChecks>(input);
                entity.OriginStatus = entity.Status;
                entity.Number = await securityChecksRepository.GetNumberAsync();
                entity.CheckUsersArray = input.CheckUsersArray.SerializeObject();
                entity.NotifyUsersArray = input.NotifyUsersArray.SerializeObject();
                entity.CCUsersArray = input.CCUsersArray.SerializeObject();
                entity.ProjectViewPortsArray = input.ProjectViewPortsArray.SerializeObject();
                //entity.SecurityChecksItemsArray = input.SecurityChecksItemsArray.SerializeObject();
                entity.SecurityChecksPropertysArray = input.SecurityChecksPropertysArray.SerializeObject();
                entity.CreatorUserId = UserManager.PrimaryId;
                input.Id = await securityChecksRepository.InsertAndGetIdAsync(entity);

                await attachmentsRepository.InsertAsync(input.AttachmentsArray, entity.Id); //巡检附件
                await SaveCheckAndFeedbacks(input.SecurityCheckAndFeedbacks, entity.Id); //整改

                await noticesAppService.SendNotice(input); //发送通知
                return entity.Id;
            }
            else
            {//2019年4月9日 14:04:58 目前不支持编辑
                var entity = await GetSecurityCheckByIdAsync(input.Id);
                //entity = ObjectMapper.Map<SecurityChecks>(input);
                //await securityCheckRepository.UpdateAsync(entity);

                //获取当前附件信息
                var attachmentsList = await attachmentsRepository.GetAllListAsync(x => x.PrimaryId == entity.Id);
                foreach (var item in attachmentsList)
                {//删除被用户删除的附件信息
                    if (!input.AttachmentsArray.Any(x => x.FileId == item.FileId))
                        await attachmentsRepository.DeleteAsync(item);
                }
            }
            return Guid.Empty;
        }

        /// <summary>
        /// 移交巡检（变更被通知人/整改人）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task TurnOverCheck(TurnOverCheckInput input)
        {
            var entity = await GetSecurityCheckByIdAsync(input.CheckId);
            var notifyUserIdList = input.NotifyUsersArray.Distinct().ToList();
            //var notifyUserList = UserManager.GetUserByIdListAsync(notifyUserIdList);//执行一些验证
            entity.NotifyUsersArray = notifyUserIdList.SerializeObject();
            await securityChecksRepository.UpdateAsync(entity);

            var history = new SecurityChecksTurnOverHistorys
            {
                CheckId = entity.Id,
                UserArray = entity.CheckUsersArray
            };
            await securityChecksTurnOverHistorysRepository.InsertAsync(history);
            await noticesAppService.SendNotice(input); //发送通知
        }

        /// <summary>
        /// 撤销巡检
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task CancelCheck(Guid input)
        {
            var entity = await GetSecurityCheckByIdAsync(input);
            if (entity.CreatorUserId != UserManager.PrimaryId) throw new UserFriendlyException(L("YouCanOnlyCancelEventsOnYou"));
            entity.Status = EnumCheckAndFeedbackStatus.已撤销;
            await securityChecksRepository.UpdateAsync(entity);
            await noticesAppService.SendNotice(ObjectMapper.Map<SecurityCheckDto>(entity)); //发送通知
        }

        /// <summary>
        /// 新建 整改回复/复查意见
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<Guid> CreateCheckAndFeedbacks(SecurityCheckAndFeedbacksInput input)
        {
            var entity = await GetSecurityCheckByIdAsync(input.CheckId);
            await noticesAppService.SendNotice(input); //发送通知
            var id = await SaveCheckAndFeedbacks(input, entity.Id);

            await securityChecksRepository.UpdateStatusAsync(entity, input.Type == EnumCheckFeedbackType.整改回复 ? EnumCheckAndFeedbackStatus.已整改 : input.Status);

            return id;
        }

        /// <summary>
        /// 批量删除巡检
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task BatchRemoveChecks(List<Guid> input)
        {
            await securityChecksRepository.BatchUpdateAsync(x => new SecurityChecks { IsDeleted = true }, x => input.Contains(x.Id));
        }

        /// <summary>
        /// 获取巡检详情
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<SecurityCheckDetailDto> QueryCheckDetailById(Guid input)
        {
            var entity = await GetSecurityCheckByIdAsync(input);

            var userIdList = new List<Guid?> { entity.CreatorUserId };
            var result = ObjectMapper.Map<SecurityCheckDetailDto>(entity);
            var checkAndFeedbacks = securityCheckAndFeedbacksRepository.GetAll().Where(x => x.CheckId == entity.Id).OrderBy(x => x.CreationTime).ToList();
            var historyList = await securityChecksTurnOverHistorysRepository.GetAllListAsync(x => x.CheckId == entity.Id); //移交记录

            result.ProjectName = projectsRepository.GetNameOrEmpty(entity.ProjectId);

            //收集各种用户标识并一次性查询出来            
            //userIdList.Add(entity.CorrectCreatorUserId);
            userIdList.AddRange(entity.CheckUsersArray); //执行检查人标识集合
            userIdList.AddRange(entity.NotifyUsersArray); //被通知人/整改人 标识集合
            userIdList.AddRange(entity.CCUsersArray); //整改抄送人标识集合
            userIdList.AddRange(historyList.Select(x => x.UserArray).ToList()); //移交接收人
            userIdList.AddRange(historyList.Select(x => x.CreatorUserId)); //移交创建人
            userIdList.AddRange(checkAndFeedbacks.Select(x => x.NotifyUsersArray)); //被通知人标识集合
            userIdList.AddRange(checkAndFeedbacks.Select(x => x.CCUsersArray)); //抄送人标识集合
            userIdList.AddRange(checkAndFeedbacks.Select(x => x.CreatorUserId)); //整改/回复 创建人

            //一次性查询出 巡检项 与 巡检性质
            var checkItemIdList = new List<Guid> { entity.CheckItemId };
            checkItemIdList.AddRange(entity.SecurityChecksPropertysArray);
            using (UnitOfWorkManager.Current.DisableFilter(AbpDataFilters.SoftDelete))
            {
                var checkItemList = securityCheckItemsRepository.GetAll().Where(x => checkItemIdList.Contains(x.Id)).ToList();
                //巡检项 与 巡检性质 名称赋值
                //result.SecurityChecksItemNames = checkItemList.GetNameList(entity.SecurityChecksItemsArray);
                result.SecurityChecksPropertyNames = checkItemList.GetNameList(entity.SecurityChecksPropertysArray);
                result.CheckItemName = checkItemList.GetNameOrEmpty(entity.CheckItemId);
            }

            //一次性查询出附件信息
            var primaryIdList = new List<Guid> { entity.Id };
            primaryIdList.AddRange(checkAndFeedbacks.Select(x => x.Id));
            var attachmentList = await attachmentsRepository.GetAll().Where(x => primaryIdList.Contains(x.PrimaryId)).ToListAsync();
            result.Attachments = attachmentList.GetUrls(entity.Id);

            //各种用户名赋值
            var userList = await UserManager.GetUserByIdListAsync(userIdList);

            result.CheckUserNames = userList.GetNameList(entity.CheckUsersArray);
            result.CreatorUserName = userList.GetNameOrEmpty(entity.CreatorUserId);
            //result.CorrectCreatorUserName = userList.GetNameOrEmpty(entity.CorrectCreatorUserId);
            result.NotifyUserNames = userList.GetNameList(entity.NotifyUsersArray);
            result.CCUserNames = userList.GetNameList(entity.CCUsersArray);
            result.TurnOverHistoryUserNames = userList.GetNameList(historyList.Select(x => x.UserArray)); //移交记录赋值

            //整改 与 复查情况
            foreach (var item in checkAndFeedbacks)
            {
                var dto = ObjectMapper.Map<SecurityCheckAndFeedbacksDto>(item);
                dto.CreatorUserName = userList.GetNameOrEmpty(item.CreatorUserId);
                dto.Attachments = attachmentList.GetUrls(item.Id);
                result.CheckAndFeedbacksList.Add(dto);
            }

            return result;
        }

        /// <summary>
        /// 获取巡检-分页数据集合
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<SecurityCheckDto>> QueryChecksPagedList(QueryChecksPagedListInput input)
        {
            return await GetChecksPagedList(input);
        }

        private bool CheckContainsUser(string usersArray)
        {
            if (usersArray.IsNullOrWhiteSpace()) return false;
            var userIdList = new List<long>();
            var values = ((JArray)JsonConvert.DeserializeObject(usersArray)).Values();
            foreach (var c in values)
            {//将筛选出来的用户标识储存到 UserIdList 变量中
                long.TryParse(c.ToString(), out var id);
                userIdList.Add(id);
            }
            return userIdList.Contains(UserManager.UserId.Value);
        }

        private async Task<PagedResultDto<SecurityCheckDto>> GetChecksPagedList(QueryChecksPagedListInput input, bool currentUser = false)
        {
            var primaryId = UserManager.PrimaryId.ToString();
            long.TryParse(input.Filter, out var number);
            var query = securityChecksRepository.GetAll()
                .WhereIf(!currentUser, x => x.ProjectId == input.ProjectId)
                .WhereIf(input.CheckItemId.HasValue, x => x.CheckItemId == input.CheckItemId)
                .WhereIf(input.Status > 0, x => x.Status == input.Status)
                .WhereIf(input.IsComplete == 1, x => x.Status >= EnumCheckAndFeedbackStatus.已完成) //只查询已完成
                .WhereIf(input.IsComplete == 2, x => x.Status < EnumCheckAndFeedbackStatus.已完成) //只查询未完成
                .WhereCreationTimeRange1(input.CreationTimeRange)
                .WhereCheckDateRange(input.CheckDateRange)
                .WhereIf(currentUser, x =>
                        //CheckContainsUser(x.CheckUsersArray) || CheckContainsUser(x.NotifyUsersArray) || CheckContainsUser(x.CCUsersArray) //这里有可能出现查询性能问题，出现时再重构
                        x.CheckUsersArray.Contains(primaryId) || x.NotifyUsersArray.Contains(primaryId) || x.CCUsersArray.Contains(primaryId)
                        )
                .WhereIf(!input.Filter.IsNullOrWhiteSpace(), x => x.Number == number || x.Content.Contains(input.Filter) || x.CorrectContent.Contains(input.Filter));

            var items = await query.OrderByDescending(x => x.CreationTime).PageByAsync(input);
            var result = ObjectMapper.Map<List<SecurityCheckDto>>(items.ToList());

            var userIdList = new List<Guid?>();
            userIdList.AddRange(items.Select(x => x.NotifyUsersArray)); //被通知人标识集合
            userIdList.AddRange(items.Select(x => x.CheckUsersArray));
            var userList = await UserManager.GetUserByIdListAsync(userIdList);

            //一次性查询出 巡检项 与 巡检性质
            var checkItemIdList = new List<Guid>();
            checkItemIdList.AddRange(items.Select(x => x.CheckItemId));
            checkItemIdList.AddRange(items.Select(x => x.SecurityChecksPropertysArray).ToArray());
            var checkItemList = securityCheckItemsRepository.GetAll().Where(x => checkItemIdList.Contains(x.Id)).ToList();

            foreach (var item in result)
            {
                var entity = userList.FirstOrDefault();
                item.CheckItemName = checkItemList.GetNameOrEmpty(item.CheckItemId);
                item.CheckUserNames = userList.GetNameList(item.CheckUsersArray);
                item.NotifyUserNames = userList.GetNameList(item.NotifyUsersArray);
                item.CCUserNames = userList.GetNameList(item.CCUsersArray);
                item.SecurityChecksPropertyNames = checkItemList.GetNameList(item.SecurityChecksPropertysArray);
            }

            return new PagedResultDto<SecurityCheckDto>(query.Count(), result);
        }

        /// <summary>
        /// 获取需要我整改的巡检-分页数据集合
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<SecurityCheckDto>> QueryMyChecksPagedList(QueryChecksPagedListInput input)
        {
            return await GetChecksPagedList(input, true);
        }

        #region Private method

        //获取巡检
        private async Task<SecurityChecks> GetSecurityCheckByIdAsync(Guid id)
        {
            var entity = await securityChecksRepository.FirstOrDefaultAsync(x => x.Id == id);
            if (entity == null) throw new UserFriendlyException(L("TheItemDoesNotExist"), L("PleaseRefreshThePageAndTryAgain"));
            return entity;
        }

        //保存整改/回复
        private async Task<Guid> SaveCheckAndFeedbacks(SecurityCheckAndFeedbacksInput input, Guid checkId)
        {
            if (input == null) return Guid.Empty;

            var notifyUsersArray = JsonConvert.DeserializeObject<List<Guid>>(input.NotifyUsersArray);
            var cCUsersArray = JsonConvert.DeserializeObject<List<Guid>>(input.CCUsersArray);

            var entity = ObjectMapper.Map<SecurityCheckAndFeedbacks>(input);
            entity.CheckId = checkId;
            entity.CreatorUserId = UserManager.PrimaryId;
            entity.NotifyUsersArray = JsonConvert.SerializeObject(notifyUsersArray);
            entity.CCUsersArray = JsonConvert.SerializeObject(cCUsersArray);

            var id = await securityCheckAndFeedbacksRepository.InsertAndGetIdAsync(entity);
            await attachmentsRepository.InsertAsync(input.AttachmentsArray, id); //整改附件
            return id;
        }

        #endregion

        #endregion

        #region 自检

        /// <summary>
        /// 新建/编辑 自检
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<Guid> CreateSelfCheck(SelfChecksInput input)
        {
            if (input.Id == Guid.Empty)
            {//新增
                var entity = ObjectMapper.Map<SelfChecks>(input);
                entity.Number = await selfChecksRepository.GetNumberAsync();
                entity.CheckUsersArray = input.CheckUsersArray.SerializeObject();
                entity.NotifyUsersArray = input.NotifyUsersArray.SerializeObject();
                entity.CCUsersArray = input.CCUsersArray.SerializeObject();
                entity.ProjectViewPortsArray = input.ProjectViewPortsArray.SerializeObject();
                entity.CreatorUserId = UserManager.PrimaryId;
                input.Id = await selfChecksRepository.InsertAndGetIdAsync(entity);
                await attachmentsRepository.InsertAsync(input.AttachmentsArray, entity.Id); //巡检附件

                await noticesAppService.SendNotice(input); //发送通知
                return entity.Id;
            }
            else
            {//编辑
                var entity = await GetSelfCheckByIdAsync(input.Id);
                if (entity.Status > input.Status) throw new UserFriendlyException("状态不能回退");

                entity.Status = input.Status;
                entity.Content = input.Content;
                entity.ProjectViewPortsArray = input.ProjectViewPortsArray.SerializeObject();
                entity.CheckUsersArray = input.CheckUsersArray.SerializeObject();
                entity.NotifyUsersArray = input.NotifyUsersArray.SerializeObject();
                entity.CCUsersArray = input.CCUsersArray.SerializeObject();
                await selfChecksRepository.UpdateAsync(entity);

                //获取当前附件信息
                var attachmentsList = await attachmentsRepository.GetAllListAsync(x => x.PrimaryId == entity.Id);
                foreach (var item in attachmentsList)
                {//删除被用户删除的附件信息
                    if (!input.AttachmentsArray.Any(x => x.FileId == item.FileId))
                        await attachmentsRepository.DeleteAsync(item);
                }
            }
            return Guid.Empty;
        }

        /// <summary>
        /// 完成自检
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task CompleteSelfCheck(Guid input)
        {
            var entity = await GetSelfCheckByIdAsync(input);
            entity.Status = EnumSelfCheckStatus.已整改;
            await selfChecksRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 撤销自检
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task CancelSelfCheck(Guid input)
        {
            var entity = await GetSelfCheckByIdAsync(input);
            if (entity.CreatorUserId != UserManager.PrimaryId) throw new UserFriendlyException(L("YouCanOnlyCancelEventsOnYou"));
            entity.Status = EnumSelfCheckStatus.已撤销;
            await selfChecksRepository.UpdateAsync(entity);
            await noticesAppService.SendNotice(ObjectMapper.Map<SelfChecksDto>(entity)); //发送通知
        }

        /// <summary>
        /// 获取自检详情
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<SelfChecksDto> QuerySelfCheckDetailById(Guid input)
        {
            var entity = await GetSelfCheckByIdAsync(input);

            //一次性查询出附件信息
            var attachmentList = await attachmentsRepository.GetAll().Where(x => x.PrimaryId == entity.Id).ToListAsync();
            var result = ObjectMapper.Map<SelfChecksDto>(entity);
            result.Attachments = attachmentList.GetUrls();
            result.ProjectName = projectsRepository.GetNameOrEmpty(entity.ProjectId);

            var userIdList = new List<Guid?> { entity.CreatorUserId };
            userIdList.AddRange(entity.NotifyUsersArray); //被通知人标识集合
            userIdList.AddRange(entity.CheckUsersArray);
            userIdList.AddRange(entity.CCUsersArray);
            var userList = await UserManager.GetUserByIdListAsync(userIdList);
            result.CheckUserNames = userList.GetNameList(entity.CheckUsersArray);
            result.CreatorUserName = userList.GetNameOrEmpty(entity.CreatorUserId);
            result.CCUserNames = userList.GetNameList(entity.CCUsersArray);
            result.NotifyUserNames = userList.GetNameList(entity.NotifyUsersArray);

            return result;
        }

        /// <summary>
        /// 获取自检-分页数据集合
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<SelfChecksDto>> QuerySelfChecksPagedList(QuerySelfChecksPagedList input)
        {
            return await GetSelfChecksPagedList(input);
        }

        /// <summary>
        /// 获取需要我们整改的自检-分页数据集合
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<SelfChecksDto>> QueryMySelfChecksPagedList(QuerySelfChecksPagedList input)
        {
            return await GetSelfChecksPagedList(input, true);
        }

        #region Private method

        /// <summary>
        /// 获取自检-分页数据集合
        /// </summary>
        /// <param name="input"></param>
        /// <param name="currentUser">是否当前用户</param>
        /// <returns></returns>
        private async Task<PagedResultDto<SelfChecksDto>> GetSelfChecksPagedList(QuerySelfChecksPagedList input, bool currentUser = false)
        {
            var primaryId = UserManager.PrimaryId.ToString();
            long.TryParse(input.Filter, out var number);
            var query = selfChecksRepository.GetAll()
                .WhereIf(!currentUser, x => x.ProjectId == input.ProjectId)
                .WhereIf(input.Status > 0, x => x.Status == input.Status)
                .WhereIf(input.IsComplete == 1, x => x.Status >= EnumSelfCheckStatus.已整改) //只查询已完成
                .WhereIf(input.IsComplete == 2, x => x.Status < EnumSelfCheckStatus.已整改) //只查询未完成
                .WhereCreationTimeRange1(input.CreationTimeRange)
                .WhereCheckDateRange(input.CheckDateRange)
                .WhereIf(currentUser, x =>
                        //CheckContainsUser(x.CheckUsersArray) || CheckContainsUser(x.NotifyUsersArray) || CheckContainsUser(x.CCUsersArray) //这里有可能出现查询性能问题，出现时再重构
                        x.CheckUsersArray.Contains(primaryId) || x.NotifyUsersArray.Contains(primaryId) || x.CCUsersArray.Contains(primaryId)
                        )
                .WhereIf(!input.Filter.IsNullOrWhiteSpace(), x => x.Number == number || x.Content.Contains(input.Filter));

            var items = await query.OrderByDescending(x => x.CreationTime).PageByAsync(input);
            var result = ObjectMapper.Map<List<SelfChecksDto>>(items.ToList());

            //用户姓名
            var userIdList = new List<Guid?>();
            userIdList.AddRange(items.Select(x => x.CreatorUserId));
            userIdList.AddRange(items.Select(x => x.CheckUsersArray));
            userIdList.AddRange(items.Select(x => x.NotifyUsersArray));
            userIdList.AddRange(items.Select(x => x.CCUsersArray));
            var userList = await UserManager.GetUserByIdListAsync(userIdList);

            //一次性查询出附件信息
            var primaryIdList = new List<Guid>();
            primaryIdList.AddRange(result.Select(x => x.Id));
            var attachmentList = await attachmentsRepository.GetAll().Where(x => primaryIdList.Contains(x.PrimaryId)).ToListAsync();

            foreach (var item in result)
            {
                item.NotifyUserNames = userList.GetNameList(item.NotifyUsersArray);
                item.CheckUserNames = userList.GetNameList(item.CheckUsersArray);
                item.CCUserNames = userList.GetNameList(item.CCUsersArray);
                item.Attachments = attachmentList.GetUrls(item.Id);
                item.CreatorUserName = userList.GetNameOrEmpty(item.CreatorUserId);
            }

            return new PagedResultDto<SelfChecksDto>(query.Count(), result);
        }

        //获取自检
        private async Task<SelfChecks> GetSelfCheckByIdAsync(Guid id)
        {
            var entity = await selfChecksRepository.FirstOrDefaultAsync(x => x.Id == id);
            if (entity == null) throw new UserFriendlyException(L("TheItemDoesNotExist"), L("PleaseRefreshThePageAndTryAgain"));
            return entity;
        }

        #endregion

        #endregion

        #region 检查项/检查性质

        /// <summary>
        /// 新建/编辑 检查项/检查性质  Type：1检查项、2检查性质
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<Guid> CreateOrModifyCheckItem(SecurityCheckItemsInput input)
        {
            var entity = new SecurityCheckItems();
            if (input.Id == Guid.Empty)
            {
                entity = ObjectMapper.Map<SecurityCheckItems>(input);
                if (input.ParentId == null) entity.ParentId = Guid.Empty;
                entity.CreatorUserId = UserManager.PrimaryId;
                await securityCheckItemsRepository.InsertAsync(entity);
            }
            else
            {
                entity = await securityCheckItemsRepository.FirstOrDefaultAsync(x => x.Id == input.Id);
                if (entity == null) throw new UserFriendlyException(L("TheItemDoesNotExist"), L("PleaseRefreshThePageAndTryAgain"));
                if (input.ParentId.HasValue) entity.ParentId = input.ParentId;
                entity.Name = input.Name.Trim();
                await securityCheckItemsRepository.UpdateAsync(entity);
            }
            return entity.Id;
        }

        /// <summary>
        /// 批量删除 检查项/检查性质
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task BatchRemoveCheckItem(List<Guid> input)
        {
            await securityCheckItemsRepository.BatchUpdateAsync(x => new SecurityCheckItems { IsDeleted = true }, x => input.Contains(x.Id));
        }

        /// <summary>
        /// 获取 检查项/检查性质 集合  Type：0检查项/检查性质、1检查项、2检查性质
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<SecurityCheckItemsDto>> QueryCheckItems(QueryCheckItemsInput input)
        {
            var result = await securityCheckItemsRepository.GetAll()
                .Where(x => x.ProjectId == input.ProjectId)
                .WhereIf(input.Type > 0, x => x.Type == input.Type)
                .WhereIf(input.ParentId.HasValue, x => x.ParentId == input.ParentId)
                .WhereIf(!input.Filter.IsNullOrWhiteSpace(), x => x.Name.Contains(input.Filter))
                .ToListAsync();

            return ObjectMapper.Map<List<SecurityCheckItemsDto>>(result);
        }

        #endregion
    }
}
